#! /usr/bin/env python
#coding=utf-8

# pylint: disable-msg=W0704

# Copyright 2008 German Aerospace Center (DLR)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

""" restrain the format of commit message. """

'''
    # 最佳实践 ::: 验证和处理分开进行, 符合人类大脑的思维方式
'''

import datetime
import re
from urllib import urlopen
import json


def run(transaction, config):
    commitMsg = transaction.getCommitMsgWithLinesep()  # getCommitMsg
    userId = transaction.getUserID()
    reversion = transaction.getRevision()
    # 
    return _analysisCommitMsg(commitMsg) 
    
def _analysisCommitMsg(commitMsg):
    commitMsgBylines = commitMsg.splitlines(False)
    if(len(commitMsgBylines) < 1):
        return (_formatErrorInfo("日志的行数不足"), 1)

    firstLine = commitMsgBylines[0].strip()
    if "FORCE" in firstLine:
        return ("强制提交, PASS", 0)
    patt = re.compile("[story|bug|task]\:\d+\s.+")
    result = re.search(patt,firstLine)
    if(result == None):
        return (_formatErrorInfo("日志的格式不对, 形如：story:31604 增加返回字段信息"), 1)
    
    #if(not _existIdInZentao(firstLine)):
    #    return (_formatErrorInfo("不存在该zentao ID, 请确认"), 1)
    return ("",0)

def _formatErrorInfo(errorInfo):
    return ("日志格式存在问题: " + errorInfo) #.decode("utf-8").encode("gbk")

def _existIdInZentao(firstLineOfMsg):
    arr = firstLineOfMsg.split(" ")[0].split(":")
    type = arr[0]
    id = arr[1]
    return zentao(type, id)

# zentao访问根路径， 
BASE_URL="http://111.11.111.11:801/zentao"
# 用户禅道密码
PASSWORD=r"CCCCCZZZZ"

######## 验证提交的禅道id是否真实存在
# 扩展方法参见:  https://devel.easycorp.cn/book/extension/api-auth-44.html
def zentao(type, id):
    sessionResult = zentao_getSessionInfo()
    sessionName = sessionResult["sessionName"]
    sessionID = sessionResult["sessionID"]
    rand = sessionResult["rand"]
    zentao_userLogin(sessionResult)
    return zentao_checkIfExistId(type,id,sessionID)

def zentao_getSessionInfo():
    response = urlopen('{}/api-getSessionID.json'.format(BASE_URL))
    #print(type(response.read()))
    #print(type(response.read().decode("UTF-8")))
    #print(json.loads(response.read().decode("UTF-8"))["data"])
    sessionResult = json.loads(response.read().decode("UTF-8"))["data"]
    return json.loads(sessionResult)

def zentao_userLogin(sessionResult):
    response = urlopen('{}/user-login.json?account=XXXX&password={}&{}={}'.format(BASE_URL,PASSWORD,sessionResult["sessionName"],sessionResult["sessionID"]))
    result = json.loads(response.read().decode("UTF-8"))
    if(result["status"] == "failed"):
        raise Exception(result["reason"])
    else:
        pass

def zentao_checkIfExistId(type, id,sessionID):
    response = urlopen('{}/{}-view-{}.json?zentaosid={}'.format(BASE_URL, type, id, sessionID))
    result = response.read().decode("UTF-8")
    #print(result)
    return not ("fail" in result and "back" in result)











	
def writeErrorLog(errorInfo):
    import datetime
    filename = "F:/_svnChecker/svnchecker-0.3/svnCommitMsg-Error-%s.log" % (datetime.datetime.now().strftime("%Y_%m_%d"))
    with open(filename, 'a') as file_object:
        file_object.write(datetime.datetime.now().strftime("%H:%M - %d.%m.%Y") + "   :  " + errorInfo.decode("utf-8").encode("gbk") + "\n")
